package com.zwy.leetcode;

public class Day06Test {
    /**
     * 二分查找
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        if(nums.length==1){
            if(nums[0]==target)return 0;
            else return -1;
        }
        int low=0;
        int height=nums.length-1;
        int mid=0;
        while(low!=height){
            mid=(low+height)/2;
            if(nums[mid]<target){
                low=mid+1;
            }
            if(nums[mid]>target){
                height=mid-1;
            }
            if(nums[mid]==target)return mid;
        }
        return nums[low]==target?mid:-1;
    }

    boolean isBadVersion(int version){
        if(version>=4)return true;
        return  false;
    }
    /**
     * 第一个错误的版本
     * @param n
     * @return
     */

    public int firstBadVersion(int n) {
        int low=1;
        int height=n;
        int mid=0;
        while(low<=height){
            mid=low+(height-low)/2;
            if(isBadVersion(mid)==false)low=mid+1;
            if(isBadVersion(mid)==true)height=mid-1;
        }
        return low;
    }

    public int searchInsert(int[] nums, int target) {
        int low=0;
        int high=nums.length-1;
        int mid=0;
        while(low<=high){
            mid=(low+high)/2;
            if(nums[mid]<target)low=mid+1;
            else if(nums[mid]>target)high=mid-1;
            else return mid;
        }
        return low;
    }

    /**
     * 977. 有序数组的平方
     * @param nums
     * @return
     */
    public int[] sortedSquares(int[] nums) {
        int []p=new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if(nums[i]*nums[i]>nums[i+1]*nums[i+1]){
                p[i]=nums[i+1]*nums[i+1];
                p[i+1]=nums[i]*nums[i];
            }
            else{
                p[i+1]=nums[i+1]*nums[i+1];
                p[i]=nums[i]*nums[i];
            }
        }
        return p;
    }





    


    public static void main(String[] args) {
        int  []arr={ 1,3,5 };
        int n=5;
        Day06Test test=new Day06Test();
        int i = test.searchInsert(arr,3);
        System.out.println(i);
    }
}
